How does python work?

Python is a scripting language; that means, broadly speaking, that to get a program running one needs two components: a script and and interpreter.

A python script is a file with the extension ".py" which is writen in plain text (for example helloworld.py) An interpreter is usually a binary file called "python" in your operative system, that you can feed your scripts to be executed. You can interact with the interpreter directly, by calling it without feeding it any scripts, and the interpreter will run the commands in the order you write them.

You can imagine the way the python interpreter works like a pianola (a player piano): it usually works with some punched rolls (the script), playing the music previously recorded; but you can also play it straight ahead, without the need for a roll.

Running a script ".py"

A very simple example can be a program that outputs "Hello world" in your console. For example, the file helloworld.py consists of the following line:

print 'Hello, World!'

If you download the file You can run it by writing in your console python helloworld.py , and the output should be

Hello, world!

Try this yourself! Download the file to a location in your system, and then run the script from the command line.

Running python as an interpreter

If you are anywhere in your system, you can access your python interpreter by writing python in your console/terminal.

You will get an output of the form:

Python 2.7.5 (default, Aug 25 2013, 00:04:04) <-- [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin <-- This might be different! Type "help", "copyright", "credits" or "license" for more information. \>\>\>

Once you are in that situation, you can just write the line that was in the file "helloworld.py" to obtain the following output:


In [1]:
print 'Hello, World!'


Hello, World!

Note that there are single quotation marks around the text you want to be shown. Using double quotation marks is also fine, but you should be consistent when using one or the other.

Exercises

You have just completed your first trip into python! Some exercises for you to practise:

  • Find the location of the python binary in your system?
  • Write a script that outputs several lines of text. You can do this by writing several print statements, or by using the character \n at the end of each line. Then, execute the script using your python interpreter.
  • Do the same multi-line output inside the interpreter, using your system console/terminal.